package com.geeksaga.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import com.geeksaga.common.constant.SagaConstants;
import com.geeksaga.domain.SagaFile;
import com.geeksaga.domain.UploadInfo;

/**
 * @author newbie
 * @since 0.1
 */
public class FileUtil {
    
    protected static final Log logger = LogFactory.getLog(FileUtil.class);
    
    public static List<SagaFile> processFile(HttpServletRequest request, List<MultipartFile> list, String code) {
        List<SagaFile> fileList = new ArrayList<SagaFile>();
        
        try {
            String path = BundleUtils.getString("GeekSaga", "UPLOAD_PATH");
            
            if(path.equals("default"))
                path = request.getSession().getServletContext().getRealPath("/upload/" + code);
            else
                path += "/" + code;
            
            File directory = new File(path);

            if(!directory.exists())
                directory.mkdirs();
            
            Iterator<MultipartFile> iterator = list.iterator();
            
            while(iterator.hasNext()) {
                MultipartFile multipartFile = iterator.next();
                
                if (multipartFile.getSize() > 0) {
                    File destination = File.createTempFile("file_", "." + FilenameUtils.getExtension(multipartFile.getOriginalFilename()), directory);
                    UploadInfo uploadInfo = (UploadInfo) request.getSession().getAttribute("uploadInfo");
                    uploadInfo.setBytesRead(FileCopyUtils.copy(multipartFile.getInputStream(), new FileOutputStream(destination)));
                    uploadInfo.setStatus("done");
                    request.getSession().setAttribute("uploadInfo", uploadInfo);
                    
                    SagaFile file = new SagaFile();
                    file.setSid(KeyGenerator.generatorBbsKey());
                    file.setTargetId(code);
                    file.setAttachOrder("1");
                    file.setOriginalName(multipartFile.getOriginalFilename());
                    file.setFileName(destination.getName());
                    file.setFileExtension(FilenameUtils.getExtension(multipartFile.getOriginalFilename()));
                    file.setFileSize(String.valueOf(multipartFile.getSize()));
                    file.setFileDesc(SagaConstants.EMPTY_VALUE);
                    file.setAttachType(SagaConstants.EMPTY_VALUE);
                    file.setDownloadCnt(SagaConstants.DEFAULT_CNT);
                    
                    fileList.add(file);
                }
            }
        } catch (MaxUploadSizeExceededException e) {
            logger.info(e.getMessage(), e);
        } catch (IOException e) {
            logger.info(e.getMessage(), e);
        }
        
        return fileList;
    }
}
